package com.jubaozan.service.platform.decorator;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jubaozan.c3.framework.utils.GsonUtil;
import com.jubaozan.c3.framework.utils.ObjectUtil;
import com.jubaozan.c3.framework.utils.PageHolder;
import com.jubaozan.c3.framework.utils.ResultHolder;
import com.jubaozan.dao.youme.domain.*;
import com.jubaozan.dao.youme.service.*;
import com.jubaozan.feign.goods.StoreGoodsFeignService;
import com.jubaozan.feign.order.OrderFeignService;
import com.jubaozan.feign.order.vo.OrderDetailVO;
import com.jubaozan.feign.order.vo.OrderSearchVO;
import com.jubaozan.feign.platform.activity.vo.ActivityLogVO;
import com.jubaozan.feign.user.UserFeignService;
import com.jubaozan.feign.user.vo.UserVO;
import com.jubaozan.service.platform.constants.ActivityStatusEnum;
import com.jubaozan.service.platform.constants.GoodsAuditEnum;
import com.jubaozan.service.platform.constants.GoodsStatusEnum;
import com.jubaozan.service.platform.exception.PlatformException;
import com.jubaozan.service.platform.vo.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.ZoneId;
import java.util.*;

/**
 * @ClassName ConsumeActivityDecorator
 * @Description 消费者活动相关Decorator
 * @Author TanRuixiang
 * @Date 2020/9/28 11:01
 * @Version 1.0
 **/
@Slf4j
@Component
@AllArgsConstructor
public class ConsumeActivityDecorator {
    private final StoreService storeService;
    private final ActivityGoodsService activityGoodsService;
    private final ActivityService activityService;
    private final StoreGoodsFeignService storeGoodsFeignService;
    private final OrderFeignService orderFeignService;
    private final ActivityLogService activityLogService;
    private final UserFeignService userFeignService;
    private final StoreUserService storeUserService;


    public Store getStoreInfo(Long userId) {
        Store store = storeService.getOne(new QueryWrapper<Store>().lambda()
                .eq(Store::getId, getStoreIdByUserId(userId)));
        logger.info("查询到平台的信息:{}",store);
        if (ObjectUtil.isEmpty(store)) {
            throw new PlatformException("个体平台不存在");
        }
        return store;
    }


    private Long getStoreIdByUserId(Long userId){
        QueryWrapper<StoreUser> qw = new QueryWrapper<>();
        qw.lambda().eq(StoreUser::getUserId,userId).orderByAsc(StoreUser::getCreateAt);
        StoreUser user = storeUserService.getOne(qw,false);
        logger.info("查询到用户关联的平台信息:{}",user);
        if(ObjectUtil.isEmpty(user)){
            throw new PlatformException("用户:"+userId+",不存在");
        }
        return user.getStoreId();
    }

    public ActivityListVO getActivityInfor(Long storeId, Integer status) {
        Activity activity = null;
        if (status.equals(ActivityStatusEnum.ING.status())) {
            //进行中的活动
            activity = getActiviting(storeId);
        } else if (status.equals(ActivityStatusEnum.EXPIRE.status())) {
            //历史活动
            activity = getHistoryActivity(storeId);
        } else if (status.equals(ActivityStatusEnum.PRE_SALE.status())) {
            //预售的
            activity = this.getPreSsleActivity(storeId);
        } else {
            throw new PlatformException("活动状态类型错误");
        }
        if (ObjectUtil.isEmpty(activity)) {
            return null;
        }
        ActivityListVO activityListVO = new ActivityListVO();
        BeanUtils.copyProperties(activity, activityListVO);
        activityListVO.setBrowseNum(this.getBrowseNum(storeId));
        activityListVO.setBrowseUserImg(getBrowseUserImg(storeId));
        return activityListVO;
    }

    public IPage<StoreGoodsVO> getGoodsListById(Long storeId, Long activityId,Long userId,PageHolder pageHolder) {
        IPage<StoreGoodsVO> voiPage = new Page<>();
        Page<ActivityGoods> page = new Page<>(pageHolder.getPageNo(), pageHolder.getPageSize());
        QueryWrapper<ActivityGoods> qw = new QueryWrapper<>();
        qw.lambda().eq(ActivityGoods::getActivityId, activityId).orderByDesc(ActivityGoods::getCreateAt);
        IPage<ActivityGoods> iPage = activityGoodsService.page(page, qw);
        List<ActivityGoods> goodsList = iPage.getRecords();
        if (!CollectionUtils.isEmpty(goodsList)) {
            voiPage.setRecords(getGoodsListByStoreId(goodsList, storeId,userId));
            voiPage.setCurrent(iPage.getCurrent());
            voiPage.setSize(iPage.getSize());
            voiPage.setPages(iPage.getPages());
            voiPage.setTotal(iPage.getTotal());
        }
        return voiPage;
    }


    public IPage<UserInfoVO> getLookingById(Long storeId, Long activityId, PageHolder pageHolder) {
        IPage<UserInfoVO> infoVOIPage = new Page<>();
        Page<ActivityLog> page = new Page<>(pageHolder.getPageNo(), pageHolder.getPageSize());
        QueryWrapper<ActivityLog> qw = new QueryWrapper<>();
        qw.lambda().eq(ActivityLog::getStoreId, storeId).eq(ActivityLog::getActivityId, activityId).orderByDesc(ActivityLog::getCreateAt);
        IPage<ActivityLog> iPage = activityLogService.page(page, qw);
        List<ActivityLog> list = iPage.getRecords();
        if (CollectionUtils.isEmpty(list)) {
            return infoVOIPage;
        }
        List<Long> userIds = new ArrayList<>(list.size());
        list.forEach(item -> {
            userIds.add(item.getUserId());
        });
        ResultHolder<List<UserVO>> holder = userFeignService.getUserByIds(userIds);
        List<UserVO> userVOList = holder.getBody();
        if (holder.isSuccess() && !CollectionUtils.isEmpty(userVOList)) {
            List<UserInfoVO> infoVOList = new ArrayList<>(userVOList.size());
            userVOList.forEach(item -> {
                UserInfoVO infoVO = new UserInfoVO();
                infoVO.setUserId(item.getId());
                infoVO.setAvatar(item.getAvatar());
                infoVOList.add(infoVO);
            });
            infoVOIPage.setRecords(infoVOList);
            infoVOIPage.setTotal(iPage.getTotal());
            infoVOIPage.setPages(iPage.getPages());
            infoVOIPage.setSize(iPage.getSize());
            infoVOIPage.setCurrent(iPage.getCurrent());
        }
        return infoVOIPage;
    }

    /**
     * @param activity: 活动对象
     * @param storeId:  平台ID
     * @return
     * @Author TanRuixiang
     * @Description 正在进行的活动
     * @Date 2020年09月28日 19:12
     **/
    public Activity getActiviting(Long storeId) {
        Activity activity = getActivityByTime(storeId, new Date());
        if (ObjectUtil.isNotEmpty(activity)) {
            return activity;
        } else {
            return getExpireActivity(storeId, new Date());
        }
    }

    /**
     * @param activity: 活动对象
     * @param storeId:  平台ID
     * @return
     * @Author TanRuixiang
     * @Description 获取上期活动(历史活动)
     * @Date 2020年09月28日 19:12
     **/
    private Activity getHistoryActivity(Long storeId) {
        Activity activity = getActivityByTime(storeId, new Date());
        //历史活动
        Date date = null;
        if (ObjectUtil.isEmpty(activity)) {
            Activity expireActivity = this.getExpireActivity(storeId, new Date());
            if (ObjectUtil.isNotEmpty(expireActivity)) {
                date = Date.from(expireActivity.getEndTime().atZone(ZoneId.systemDefault()).toInstant());
            } else {
                return expireActivity;
            }
        } else {
            date = Date.from(activity.getEndTime().atZone(ZoneId.systemDefault()).toInstant());

        }
        return getExpireActivity(storeId,date);
    }

    /**
     * @param storeId:平台ID
     * @return
     * @Author TanRuixiang
     * @Description 获取浏览数
     * @Date 2020年09月28日 14:21
     **/
    private Long getBrowseNum(Long storeId) {
        ActivityLogVO logVO = getActivityByStoreId(storeId);
        if (ObjectUtil.isEmpty(logVO)) {
            return 0L;
        }
        return logVO.getBrowseNum();
    }


    /**
     * @param storeId: 门店ID
     * @return
     * @Author TanRuixiang
     * @Description 根据平台id获取活动信息
     * @Date 2020年09月24日 15:01
     **/
    public ActivityLogVO getActivityByStoreId(Long storeId) {
        //根据门店ID查询正在进行的活动
        Activity activity = getActivityByTime(storeId, new Date());
        if (ObjectUtil.isEmpty(activity)) {
            return null;
        }
        ActivityLogVO log = new ActivityLogVO();
        int browseNum = activityLogService.count(new QueryWrapper<ActivityLog>()
                .eq("store_id", storeId)
                .eq("activity_id", activity.getId()));
        log.setBrowseNum(Long.valueOf(String.valueOf(browseNum)));
        log.setId(activity.getId());
        log.setEndTime(activity.getEndTime());
        return log;
    }


    private List<OrderVO> getBuyUser(Long goodsId, Long storeId) {
        try{
            Integer pageSize = 10;
            Integer pageNo = 0;
            OrderSearchVO searchVO = new OrderSearchVO();
            searchVO.setGoodsId(goodsId);
            Set<Long> storeIds = new HashSet<>(1);
            storeIds.add(storeId);
            searchVO.setStoreIds(storeIds);
//            searchVO.setStatus(PlatformConstants.PAYED);
            ResultHolder<Page<OrderDetailVO>> holder = orderFeignService.search(searchVO, pageSize, pageNo);
            List<OrderDetailVO> orderList = holder.getBody().getRecords();
            if (holder.isSuccess() && !CollectionUtils.isEmpty(orderList)) {
                List<OrderVO> list = new ArrayList<>(orderList.size());
                orderList.forEach(item -> {
                    OrderVO orderVO = new OrderVO();
                    orderVO.setAvatar(item.getBuyerFaceIcon());
                    orderVO.setCreateAt(item.getCreateAt());
                    orderVO.setNick(item.getBuyerName());
                    orderVO.setGoodsName(item.getItems().get(0).getGoodsName());
                    list.add(orderVO);
                });
                return list;
            }
        }catch (Exception e){
            logger.error("查询订单异常:",e);
        }
        return Collections.emptyList();
    }

    private List<StoreGoodsVO> getGoodsListByStoreId(List<ActivityGoods> list, Long storeId,Long userId) {
        List<Long> goodsIds = new ArrayList<>(list.size());
        list.forEach(item -> {
            goodsIds.add(item.getGoodsId());
        });
        ResultHolder<List<com.jubaozan.feign.goods.vo.StoreGoodsVO>> holder = storeGoodsFeignService.listGoodsByIds(goodsIds, storeId,userId);
        logger.info("获取到商品信息:{}",holder);
        List<com.jubaozan.feign.goods.vo.StoreGoodsVO> goodsList = holder.getBody();
        if (holder.isSuccess() && !CollectionUtils.isEmpty(goodsList)) {
            List<StoreGoodsVO> resultList = new ArrayList<>(goodsList.size());
            goodsList.forEach(item -> {
                resultList.add(packageStoreGoods(item,storeId));
            });
            return resultList;
        }
        return Collections.emptyList();
    }

    /**
     * 封装商品信息
     * @param item
     * @param storeId
     * @return
     */
    private StoreGoodsVO packageStoreGoods(com.jubaozan.feign.goods.vo.StoreGoodsVO item,Long storeId){
        StoreGoodsVO storeGoodsVO = new StoreGoodsVO();
        BeanUtils.copyProperties(item, storeGoodsVO);
        retailPriceToDouble(storeGoodsVO,item);
        if(item.getStatus().equals(GoodsStatusEnum.GOODS_HAS_PUBLISH.status()) &&
                item.getAuditStatus().equals(GoodsAuditEnum.YES_AUDIT.status())){
            storeGoodsVO.setFinalStatus(GoodsStatusEnum.GOODS_HAS_PUBLISH.status());
        }else{
            storeGoodsVO.setFinalStatus(GoodsStatusEnum.NOTGOODS_HAS_PUBLISH.status());
        }
        List<OrderVO> orderVOList = this.getBuyUser(item.getId(), storeId);
        storeGoodsVO.setOrderList(CollectionUtils.isEmpty(orderVOList)?Collections.emptyList():orderVOList);
        return storeGoodsVO;
    }

    private void retailPriceToDouble(StoreGoodsVO storeGoodsVO,com.jubaozan.feign.goods.vo.StoreGoodsVO item){
        BigDecimal min = new BigDecimal(item.getMinRetailPrice());
        min = min.setScale(2,BigDecimal.ROUND_HALF_UP);
        storeGoodsVO.setMinRetailPrice(min);
        BigDecimal max = new BigDecimal(item.getMaxRetailPrice());
        max = max.setScale(2,BigDecimal.ROUND_HALF_UP);
        storeGoodsVO.setMaxRetailPrice(max);
    }
    /**
     * @param storeId:平台ID
     * @param userId:用户ID
     * @param goodsId:商品ID
     * @return
     * @Author TanRuixiang
     * @Description 获取活动平台的商品信息
     * @Date 2020年09月29日 10:59
     **/
    public StoreGoodsDetailVO getGoodsDetail(Long userId, Long goodsId) {
        Long storeId = getStoreIdByUserId(userId);
        Activity activity = getActivityByTime(storeId, new Date());
        StoreGoodsDetailVO detailVO = new StoreGoodsDetailVO();
        if (ObjectUtil.isNotEmpty(activity) && getGoodsIdsByActivityId(activity.getId(), goodsId)) {
            ActivityInfoVO activityInfoVO = new ActivityInfoVO();
            BeanUtils.copyProperties(activity, activityInfoVO);
            detailVO.setActivityInfoVO(activityInfoVO);
        } else {
            activity = getExpireActivity(storeId, new Date());
            if (ObjectUtil.isNotEmpty(activity) && getGoodsIdsByActivityId(activity.getId(), goodsId)) {
                ActivityInfoVO activityInfoVO = new ActivityInfoVO();
                BeanUtils.copyProperties(activity, activityInfoVO);
                detailVO.setActivityInfoVO(activityInfoVO);
            }
        }
        ResultHolder<com.jubaozan.feign.goods.vo.StoreGoodsVO> holder = storeGoodsFeignService.getStoreGoodsById(storeId, goodsId);
        logger.info("获取商品信息:{}",holder);
        com.jubaozan.feign.goods.vo.StoreGoodsVO goodsVO = holder.getBody();
        if (holder.isSuccess() && ObjectUtil.isNotEmpty(goodsVO)) {
            BeanUtils.copyProperties(goodsVO, detailVO);
        } else {
            return null;
        }
        if(ObjectUtil.isNotEmpty(activity)){
            putBrowseLogByStoreId(activity.getId(), storeId, userId, goodsId);
        }
        return detailVO;
    }

    /**
     * @param storeId: 门店ID
     * @param userId:  用户ID
     * @return
     * @Author TanRuixiang
     * @Description 新增个体平台活动日志记录
     * @Date 2020年09月24日 15:05
     **/
    public Boolean putBrowseLogByStoreId(Long id, Long storeId, Long userId, Long goodsId) {
        //根据门店ID查询正在进行的活动
        QueryWrapper<ActivityLog> qw = new QueryWrapper<>();
        qw.lambda().eq(ActivityLog::getUserId,userId).eq(ActivityLog::getStoreId,storeId).eq(ActivityLog::getActivityId,id);
        ActivityLog log = activityLogService.getOne(qw);
        if (ObjectUtil.isNotEmpty(log)) {
            return false;
        }
        log = new ActivityLog();
        log.setActivityId(id);
        log.setStoreId(storeId);
        log.setUserId(userId);
        log.setGoodsId(goodsId);
        Map map = new HashMap();
        map.put("store_id", storeId);
        map.put("user_id", userId);
        map.put("goods_id", goodsId);
        map.put("activity_id", id);
        log.setLogMsg(GsonUtil.toJson(map));
        return activityLogService.save(log);

    }

    /**
     * @param storeId:    平台ID
     * @param goodsId:    商品ID
     * @param pageHolder: 分页
     * @return
     * @Author TanRuixiang
     * @Description 获取商品的购买记录列表
     * @Date 2020年09月29日 11:38
     **/
    public IPage<OrderVO> getBuyInfor(Long storeId, Long goodsId, PageHolder pageHolder) {
        OrderSearchVO orderSearchVO = new OrderSearchVO();
        Set<Long> storeIds = new HashSet<>(1);
        storeIds.add(storeId);
        orderSearchVO.setStoreIds(storeIds);
        orderSearchVO.setGoodsId(goodsId);
        ResultHolder<Page<OrderDetailVO>> holder = orderFeignService.search(orderSearchVO, pageHolder.getPageSize(), pageHolder.getPageNo()-1);
        logger.info("获取到订单信息:{}", JSONObject.toJSONString(holder));
        Page<OrderDetailVO> voPage = holder.getBody();
        if (holder.isSuccess() && ObjectUtil.isNotEmpty(voPage) && !CollectionUtils.isEmpty(voPage.getRecords())) {
            List<OrderDetailVO> list = voPage.getRecords();
            IPage<OrderVO> page = new Page<>();
            List<OrderVO> resultList = new ArrayList<>();
            list.forEach(item -> {
                OrderVO orderVO = new OrderVO();
                orderVO.setNick(item.getBuyerName());
                orderVO.setCreateAt(item.getCreateAt());
                orderVO.setAvatar(item.getBuyerFaceIcon());
                item.getItems().forEach(orderItemVO -> {
                    if (orderItemVO.getGoodsId().equals(goodsId)) {
                        orderVO.setGoodsName(orderItemVO.getSkuPropertiesName());
                        orderVO.setNum(orderItemVO.getQuantity());
                    }
                });
                resultList.add(orderVO);
            });
            logger.info("storeId:{},goodsId:{},获取到商品购买记录:{}",storeId,goodsId,resultList);
            page.setRecords(resultList);
            page.setCurrent(voPage.getCurrent());
            page.setSize(voPage.getSize());
            page.setPages(voPage.getPages());
            page.setTotal(voPage.getTotal());
            return page;
        }
        return new Page<>();
    }

    /**
     * @param storeId: 平台ID
     * @param goodsId: 商品ID
     * @return
     * @Author TanRuixiang
     * @Description 判断商品是否在正在进行的活动中, 如果不在则找最近的一场过期活动在判断是否在活动中。
     * @Date 2020年09月28日 19:43
     **/
    public Boolean isExistGoodsInActivity(Long storeId, Long goodsId) {
        Activity activity = this.getActivityByTime(storeId, new Date());
        //未查询到正在进行的活动
        if (ObjectUtil.isEmpty(activity)) {
            //查询最近的一场过期活动
            activity = this.getExpireActivity(storeId, new Date());
            if (ObjectUtil.isEmpty(activity)) {
                return false;
            } else {
                //判断商品是否在活动中
                return getGoodsIdsByActivityId(activity.getId(), goodsId);
            }
        }
        //查询到正在进行的活动,判断商品是否在活动中
        Boolean isExist = getGoodsIdsByActivityId(activity.getId(), goodsId);
        if (!isExist) {
            //不存在,查询最近的一场过期活动判断商品是否在活动中
            activity = getExpireActivity(storeId, new Date());
            return getGoodsIdsByActivityId(activity.getId(), goodsId);
        }
        return true;
    }

    /**
     * @param id:      活动ID
     * @param goodsId: 商品ID
     * @return
     * @Author TanRuixiang
     * @Description 判断商品是否在活动中
     * @Date 2020年09月28日 19:43
     **/
    private Boolean getGoodsIdsByActivityId(Long id, Long goodsId) {
        QueryWrapper<ActivityGoods> qw = new QueryWrapper<>();
        qw.lambda().eq(ActivityGoods::getActivityId, id).eq(ActivityGoods::getGoodsId, goodsId);
       ActivityGoods goods =  activityGoodsService.getOne(qw);
       logger.info("activityId:{},goodsId:{},获取到活动中的商品信息:{}",id,goodsId,goods);
        if (ObjectUtil.isEmpty(goods)) {
            return false;
        }
        return true;
    }

    /**
     * @param storeId:
     * @return
     * @Author TanRuixiang
     * @Description 获取预售的活动
     * @Date 2020年09月29日 8:50
     **/
    private Activity getPreSsleActivity(Long storeId) {
        QueryWrapper<Activity> qw = new QueryWrapper<>();
        qw.lambda().eq(Activity::getStoreId, storeId).ge(Activity::getStartTime, new Date()).orderByAsc(Activity::getStartTime);
        return activityService.getOne(qw, false);
    }

    /**
     * @param storeId: 平台ID
     * @param date:    时间
     * @return
     * @Author TanRuixiang
     * @Description 获取过期活动列表
     * @Date 2020年09月28日 11:27
     **/
    private Activity getExpireActivity(Long storeId, Date date) {
        QueryWrapper<Activity> qw = new QueryWrapper<>();
        qw.lambda().eq(Activity::getStoreId, storeId).lt(Activity::getEndTime, date).orderByDesc(Activity::getEndTime);
        return activityService.getOne(qw, false);
    }

    /**
     * @param storeId: 平台ID
     * @param date:    时间
     * @return
     * @Author TanRuixiang
     * @Description 根据时间获取这个时间区间是否有活动
     * @Date 2020年09月29日 9:31
     **/
    public Activity getActivityByTime(Long storeId, Date date) {
        QueryWrapper<Activity> qw = new QueryWrapper<>();
        qw.lambda().eq(Activity::getStoreId, storeId).le(Activity::getStartTime, date).ge(Activity::getEndTime, date);
        return activityService.getOne(qw);
    }


    /**
     * @param storeId:
     * @return
     * @Author TanRuixiang
     * @Description 查询用户图像
     * @Date 2020年09月28日 14:28
     **/
    public List<String> getBrowseUserImg(Long storeId) {
        //根据门店ID查询正在进行的活动
        Activity activity = getActivityByTime(storeId, new Date());
        if (ObjectUtil.isEmpty(activity)) {
            return Collections.emptyList();
        }
        IPage<ActivityLog> page = new Page<>(1, 10);
        IPage<ActivityLog> logIPage = activityLogService.page(page, new QueryWrapper<ActivityLog>()
                .eq("store_id", storeId)
                .eq("activity_id", activity.getId())
                .orderByDesc("create_at"));
        if (CollectionUtils.isEmpty(logIPage.getRecords())) {
            return Collections.emptyList();
        }
        List<ActivityLog> list = logIPage.getRecords();
        List<Long> userIds = new ArrayList<>(list.size());
        list.forEach(item -> {
            userIds.add(item.getUserId());
        });
        ResultHolder<List<UserVO>> holder = userFeignService.getUserByIds(userIds);
        logger.info("查询用户图像,获取用户信息接口:{}",holder);
        List<UserVO> userList = holder.getBody();
        if (holder.isSuccess() && !CollectionUtils.isEmpty(userList)) {
            List<String> imgList = new ArrayList<>(userList.size());
            userList.forEach(item -> {
                if(ObjectUtil.isNotEmpty(item)){
                    imgList.add(item.getAvatar());
                }
            });
            return imgList;
        }
        return Collections.emptyList();
    }
}
